package com.cssw.fyzb.busi.api.acct;

import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.busi.service.acct.RedPackService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author zhouxu
 * @create 2020-12-23 22:13
 */
@Function(description = "直播间抢红包", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true),
        @Parameter(name = "redPackId", type = Type.String, description = "红包标识", required = true),

})
@Component
public class RedPackLiveTake implements Action {

    private static final Logger logger = LoggerFactory.getLogger(RedPackLiveTake.class);

    @Autowired
    private RedPackService redPackService;

    @Autowired
    SimpleLockFactory simpleLockFactory;

    @Override
    public Response execute(Request request) throws Exception {
        Long userId = request.getLong("userId");
        Long redPackId = request.getLong("redPackId");

        // 获取锁
        SimpleLock lock = simpleLockFactory.getLock("USER_"+userId);

        try {
            lock.acquire();
            Double money = redPackService.takeRedPack(userId, redPackId);
            return Response.success().put("data", money);
        } catch (BizException biz) {
            logger.error(biz.getErrMsg(), biz.getErrCode());
            return Response.fail(biz.getErrMsg(), biz.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail(e);
        } finally {
            lock.release();
        }

    }
}
